package cn.ecut.dzy.lock.tools;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @program: java-interview
 * @description:信号量Demo
 * @author: DingZhenYun
 * @create: 2021-10-24 19:04
 **/

public class SemaphoreDemo {
    public static void main(String[] args) {

        /**
         * 初始化一个信号量为3，默认是false 非公平锁， 模拟3个停车位
         */
        Semaphore semaphore=new Semaphore(3,false);
        for(int i=1;i<=6;i++){
            new Thread(()->{
                // 抢占
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "\t 抢到车位");

                    // 每个车停3秒
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "\t 离开车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    // 释放停车位
                    semaphore.release();
                }
            },String.valueOf(i)).start();
        }
    }
}
